from typing import List, Dict, Any
import random
import numpy as np

class Agent:
    def __init__(self, agent_id: int, group_id: int, initial_opinion: float, 
                 activity_score: float, influence_score: float, emotional_stability: float):
        self.agent_id = agent_id
        self.group_id = group_id
        self.opinion = initial_opinion  # 观点值在[-1, 1]之间
        self.confidence = influence_score  # 使用影响力分数作为自信度
        self.activity_score = activity_score  # 使用活跃度分数
        self.emotional_stability = emotional_stability  # 情绪稳定性
        self.influence_score = influence_score  # 添加影响力分数属性
        self.expression_history = []  # 记录观点表达历史
        
    def observe_neighbors(self, neighbors: List['Agent']) -> Dict[str, Any]:
        """观察邻居的观点和行为"""
        neighbor_opinions = [n.opinion for n in neighbors]
        neighbor_weights = [n.influence_score for n in neighbors]  # 考虑邻居的影响力
        weighted_avg = np.average(neighbor_opinions, weights=neighbor_weights) if neighbor_opinions else 0
        return {
            "neighbors": neighbors,
            "avg_opinion": weighted_avg
        }
        
    def calculate_social_pressure(self, avg_neighbor_opinion: float) -> float:
        """计算社交压力"""
        # 社交压力 = (邻居加权平均观点 - 当前观点) * 自信度 * 情绪稳定性
        return (avg_neighbor_opinion - self.opinion) * self.confidence * self.emotional_stability
        
    def update_opinion(self, social_pressure: float) -> None:
        """更新观点"""
        # 观点更新 = 当前观点 + 社交压力 * 活跃度
        self.opinion += social_pressure * self.activity_score
        # 确保观点在[-1, 1]范围内
        self.opinion = np.clip(self.opinion, -1, 1)
        
    def decide_to_speak(self) -> bool:
        """决定是否表达观点"""
        # 基于自信度、观点强度和情绪稳定性决定是否表达
        expression_prob = (self.confidence * abs(self.opinion) * self.emotional_stability)
        return random.random() < expression_prob
        
    def get_state(self) -> Dict[str, Any]:
        """获取智能体当前状态"""
        return {
            "agent_id": self.agent_id,
            "group_id": self.group_id,
            "opinion": self.opinion,
            "confidence": self.confidence,
            "activity_score": self.activity_score,
            "emotional_stability": self.emotional_stability,
            "expression_history": self.expression_history
        } 